import React, { forwardRef, useImperativeHandle, useRef, useState, useMemo } from 'react';
import ProTable from '@ant-design/pro-table';
import classnames from 'classnames';
import { cloneDeep } from 'lodash-es';
import ColumnControlButton from './ColumnControlButton';
import styles from './CustomerTable.less';

/**
 * @name 表格组件
 * @param { Function } request 返回的结果集数据结果必须严格按照以下格式：{ success: true, data: { list: [], total: 10 } }
 * @param { Boolean } columnControl 表格列控制
 * ? 更多配置：https://procomponents.ant.design/components/table
 */
const CustomerTable = (
  {
    className,
    columns = [],
    rowKey = 'id',
    pagination = {
      showQuickJumper: true,
      defaultPageSize: 10,
      pageSizeOptions: [10, 20, 50],
    },
    scroll = {
      // scrollToFirstRowOnChange: false,
      x: false,
    },
    request = () => {},
    search = false,
    options = false,
    toolbar = {},
    size = 'large',
    columnControl = false,
    revalidateOnFocus = false,
    ...props
  },
  ref,
) => {
  const actionRef = useRef();
  const [cacheColumns, setCacheColumns] = useState(columns);
  useImperativeHandle(
    ref,
    () => ({
      // * 刷新
      reload: () => {
        actionRef.current.reload();
      },
      // * 刷新并清空,页码也会重置，不包括表单
      reloadAndRest: () => {
        actionRef.current.reloadAndRest();
      },
    }),
    [actionRef],
  );

  const onChangeColumns = (item, checked) => {
    const { dataIndex } = item;
    const newCacheColumns = cloneDeep(cacheColumns);
    newCacheColumns.map((t) => {
      const itx = t;
      if (itx.dataIndex === dataIndex) {
        itx.hideInTable = checked;
      }
      return null;
    });
    setCacheColumns(newCacheColumns);
  };

  const cacheToolbar = useMemo(() => {
    const mergeToolbar = toolbar;
    if (columnControl) {
      const baseToolbar = [<ColumnControlButton key={0} columns={cacheColumns} onChangeColumns={onChangeColumns} />];
      mergeToolbar.actions = [].concat(mergeToolbar.actions ?? [], baseToolbar);
    }
    return mergeToolbar;
  }, [toolbar, columnControl, columns]);

  /**
   * @name 表格接口请求数据
   * @param { Object } params
   * @param {*} srot
   * @param {*} filter
   * @returns { Object } 数据结构： { success: true, data: [], total: 10 }
   */
  const requestProp = async (params, srot, filter) => {
    try {
      const newParams = Object.assign({}, params, {
        pageNum: params.current,
      });
      delete newParams.current;
      const { success, data = [], totalCount = 0 } = await request(newParams, srot, filter);
      return {
        success,
        data,
        total: totalCount,
      };
    } catch (error) {
      return {
        success: false,
        data: [],
        total: 0,
      };
    }
  };

  return (
    <ProTable
      actionRef={actionRef}
      className={classnames([styles.taskProTable, className])}
      size={size}
      scroll={scroll}
      columns={cacheColumns}
      rowKey={rowKey}
      options={options}
      revalidateOnFocus={revalidateOnFocus}
      pagination={pagination}
      search={search}
      toolbar={cacheToolbar}
      request={requestProp}
      {...props}
    />
  );
};

export default React.memo(forwardRef(CustomerTable));
